class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      filterValue:'',
      filterShowStock: false,
      list: []
    }
    this.handleChange = this.handleChange.bind(this);
    this.handleFilterShowStockChange = this.handleFilterShowStockChange.bind(this);
  }
  componentDidMount() {
    var _this = this;
    $.getJSON('data.json', function(data){
      _this.setState({
        list: data
      })
    });
  } 
  handleChange(e) {
    this.setState({
      filterValue: e.target.value
    })
  }
  handleFilterShowStockChange(e) {
    this.setState({
      filterShowStock: e.target.checked
    })
  }  
  render() {
    const filterValue = this.state.filterValue;
    const filterShowStock = this.state.filterShowStock;
    const filterList = this.state.list.filter( item => {
      return item.name.indexOf(filterValue) > -1;
    }).filter( item=> {
      if( !filterShowStock ) {
        return true;
      }
      else {
        return item.stocked;
      }
    });
    return (
      <div className="app">
        <div className="search-box">
          <input placeholder="Search..." 
            value={this.state.filterValue}
            onChange={this.handleChange}
            />
          <div> 
            <label>
              <input type="checkbox" 
                checked={this.state.filterShowStock}
                onChange={this.handleFilterShowStockChange}
                />
               Only show products in stock 
            </label>
          </div>
        </div>
        <div className="list-box">
          <table>
            <thead>
              <tr>
                <th>Name</th>
                <th>price</th>
              </tr>
            </thead>
            <tbody>
              { 
                filterList.map( item => 
                  <tr key={item.name}>
                   <td className={item.stocked ? '' : 'red'}>{item.name}</td>
                   <td>{item.price}</td>
                  </tr>
                )
              }
            </tbody>
          </table>
        </div>
      </div>
    );
  }
}
ReactDOM.render(
  <App />,
  document.getElementById('root')
);